package com.wehealth;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.wehealth.dm.User;
import com.wehealth.widget.GridChart;
import com.wehealth.widget.PressureGridChart;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


@SuppressLint("ResourceAsColor")
public class HealthReport extends Fragment {	
	private MainActivity context;
	private PressureGridChart bloodPressure;
	private GridChart sugarChartBefore;
	private GridChart sugarChartAfter;
	private GridChart weightChart;
	private static  String JSONResultPressure;
	private static  String JSONResultSugarBefore;
	private static  String JSONResultSugarAfter;
	private static  String JSONResultWeight;
	private User user;
	
	private String[]  pressureMinVaules;
	private String[]  pressureMaxVaules;
	private String[]  sugarValuesAfter;
	private String[]  sugarVaules;
	private String[]  weightVaules;

	public  HealthReport()
	{
		
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.health_report, null);
	}

	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
		pressureMinVaules = new String[7];
		pressureMaxVaules = new String[7];
		sugarVaules = new String[7];
		sugarValuesAfter = new String[7];
		weightVaules = new String[7];
		
		MainActivity activity = (MainActivity)getActivity();
		context = activity;
		user = context.getUserInfo();
		
		bloodPressure = (PressureGridChart)context.findViewById(R.id.health_report_press_chart);
		sugarChartBefore = (GridChart)context.findViewById(R.id.health_report_sugar_before_chart);
		sugarChartAfter = (GridChart)context.findViewById(R.id.health_report_sugar_after_chart);
		weightChart = (GridChart)context.findViewById(R.id.health_report_weight_chart);
		
		
		connectServerGetData();
		
	}
	
	
	
	
	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message paramMessage) {
			super.handleMessage(paramMessage);

				switch (paramMessage.what) {
				case 0:
					BindBloodPressureValue(JSONResultPressure);
					break;
				case 1:
					BindSugarBeforeValue(JSONResultSugarBefore);
					break;
				case 2:
					BindSugarAfterValue(JSONResultSugarAfter);
					break;
				case 3:
					BindWeightValue(JSONResultWeight);
					break;
				default:
					break;
				}
		
		
		}
	};
	
	
	private void connectServerGetData(){
		//SIMMON_ADD
		new Thread(){
			@Override
			public void run(){
				try {
					GetBloodPressureeData();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			Message msg = new Message();
			msg.what=0;
			handler.sendMessage(msg);
			}
		}.start();
		
				new Thread(){
					@Override
					public void run(){
						try {
							GetSugarBeforeData();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					Message msg = new Message();
					msg.what=1;
					handler.sendMessage(msg);
					}
			}.start();
		
			new Thread(){
				@Override
				public void run(){
					try {
						GetSugarAfterData();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				Message msg = new Message();
				msg.what=2;
				handler.sendMessage(msg);
				}
		}.start();
		
		
		new Thread(){
			@Override
			public void run(){
				try {
					GetWeightData();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			Message msg = new Message();
			msg.what=3;
			handler.sendMessage(msg);
			}
	}.start();
	}

	/************************************************************
	 * 高压值
	 * *************************************************************/
	private void  GetBloodPressureeData() throws IOException
	{

		String userID =String.valueOf(user.getUserId());
		String httpUrl = com.wehealth.util.GetUrl.Report_GetBP_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 params.add(new BasicNameValuePair("userID",userID));
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );		
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResultPressure = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","JSONResultSugarBefore ="+JSONResultSugarBefore);
			 }
		 }
		 catch(Exception e)
		 {		
			 Log.e("error:",  e.toString()); 
		 }
	}
	
	

	   private void BindBloodPressureValue(String strJSON){
	       try{
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                JSONArray  aNews =  new JSONArray( jsonObject.getString("result") );  
	                for(int i=0; i<aNews.length(); i++){
	                	pressureMinVaules[i]=aNews.getJSONObject(i).getString("min");
	                	pressureMaxVaules[i]=aNews.getJSONObject(i).getString("max");
	                }
	                updateBloodPressureValue();
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }

	private void updateBloodPressureValue(){
	    String[] values = context.getResources().getStringArray(R.array.grid_chart_pressure_value);
	    
	    bloodPressure.setResultValues(pressureMaxVaules,200,values);
	    bloodPressure.setResultValuesBlue(pressureMinVaules,200);
	}
	
	
	
	
	/************************************************************
	 * 饭前血糖
	 * *************************************************************/
	private void  GetSugarBeforeData() throws IOException
	{

		String userID =String.valueOf(user.getUserId());
		String isGLUAC = "1";
		String httpUrl = com.wehealth.util.GetUrl.Report_GetBG_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 params.add(new BasicNameValuePair("userID",userID));
		 params.add(new BasicNameValuePair("isGLUAC",isGLUAC)); 
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );		
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResultSugarBefore = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","JSONResultSugarBefore ="+JSONResultSugarBefore);
			 }
		 }
		 catch(Exception e)
		 {		
			 Log.e("error:",  e.toString()); 
		 }
	}
	
	

	   private void BindSugarBeforeValue(String strJSON){
	       try{
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                JSONArray  aNews =  new JSONArray( jsonObject.getString("result") );  
	                for(int i=0; i<aNews.length(); i++){
	                	sugarVaules[i]=aNews.getJSONObject(i).getString("value");
	                }
	                updateSugarCharBeforeValue();
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }

	private void updateSugarCharBeforeValue(){
	    String[] values = context.getResources().getStringArray(R.array.grid_chart_sugar_value);
	    sugarChartBefore.setResultValues(sugarVaules,20,values);
	}
	
	/************************************************************
	 * 饭后血糖
	 * *************************************************************/
	private void  GetSugarAfterData() throws IOException{
		String userID =String.valueOf(user.getUserId());
		String isGLUAC = "0";
		String httpUrl = com.wehealth.util.GetUrl.Report_GetBG_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 params.add(new BasicNameValuePair("userID",userID));
		 params.add(new BasicNameValuePair("isGLUAC",isGLUAC)); 
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );		
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResultSugarAfter = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","JSONResultSugarAfter ="+JSONResultSugarAfter);
			 }
		 }
		 catch(Exception e)
		 {		
			 Log.e("error:",  e.toString()); 
		 }
	}
	
	   private void BindSugarAfterValue(String strJSON){
	       try{
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                JSONArray  aNews =  new JSONArray( jsonObject.getString("result") );  
	                for(int i=0; i<aNews.length(); i++){
	                	sugarValuesAfter[i]=aNews.getJSONObject(i).getString("value");
	                }
	                
	                updateSugarCharAfterValue();
	                
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }
	

	private void updateSugarCharAfterValue(){
	    String[] values = context.getResources().getStringArray(R.array.grid_chart_sugar_value);
	    sugarChartAfter.setResultValues(sugarValuesAfter,20,values);
	}
	
	/************************************************************
	 * 体重
	 * *************************************************************/
	private void  GetWeightData() throws IOException{
		String userID =String.valueOf(user.getUserId());
		String httpUrl = com.wehealth.util.GetUrl.Report_GetWeight_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 params.add(new BasicNameValuePair("userID",userID));
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );		
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResultWeight = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","JSONResultWeight ="+JSONResultWeight);
			 }
		 }
		 catch(Exception e)
		 {		
			 Log.e("error:",  e.toString()); 
		 }
	}
	
	   private void BindWeightValue(String strJSON){
	       try{
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                JSONArray  aNews =  new JSONArray( jsonObject.getString("result") );  
	                for(int i=0; i<aNews.length(); i++){
	                	weightVaules[i]=aNews.getJSONObject(i).getString("weight");
	                }
	                
	                updateWeightValue();
	                
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }
	
	
	
	private void updateWeightValue(){
	    String[] values = context.getResources().getStringArray(R.array.grid_chart_weight_value);
	    weightChart.setResultValues(weightVaules,200,values);
	}	
 
}
